package com.chy.blog_server.modular.web.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chy.blog_server.core.util.UploadFileUtil;
import com.chy.blog_server.core.util.UploadURLUtil;
import com.chy.blog_server.core.util.UserUtil;
import com.chy.blog_server.modular.system.entity.SysUser;
import com.chy.blog_server.modular.web.entity.BoArticle;
import com.chy.blog_server.modular.web.entity.BoArticleTag;
import com.chy.blog_server.modular.web.entity.BoFile;
import com.chy.blog_server.modular.web.entity.BoImgLog;
import com.chy.blog_server.modular.web.mapper.BoArticleMapper;
import com.chy.blog_server.modular.web.service.IBoArticleService;
import com.chy.blog_server.modular.web.service.IBoArticleTagService;
import com.chy.blog_server.modular.web.service.IBoFileService;
import com.chy.blog_server.modular.web.service.IBoImgLogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 描述：文章表 service业务层
 * 作者：chenhuiyan
 * 时间：2020/03/01 12:03
 */
@Service
@Transactional(readOnly = true)
public class BoArticleServiceImpl extends ServiceImpl<BoArticleMapper, BoArticle> implements IBoArticleService {

    @Autowired
    private IBoImgLogService boImgLogService;

    @Autowired
    private IBoArticleTagService boArticleTagService;

    @Autowired
    private IBoFileService boFileService;

    private final static Logger logger = LoggerFactory.getLogger(BoArticleServiceImpl.class);

    /**
     * 查询列表
     * @param params
     * @return
     */
    public List<Map<String, Object>> list(Map<String, Object> params){
        return baseMapper.list(params);
    }

    /**
     * 查询总数
     * @param params
     * @return
     */
    public int getCount(Map<String, Object> params){
        return baseMapper.getCount(params);
    }

    /**
     * 查询待审列表
     * @param params
     * @return
     */
    public List<Map<String, Object>> auditList(Map<String, Object> params){
        return baseMapper.auditList(params);
    }

    /**
     * 根据id查询详情
     * @param id
     * @return
     */
    public Map<String, Object> getInfoById(String id){
        return baseMapper.getInfoById(id);
    }

    /**
     * 保存
     * @param boArticle
     * @param imgName 保存编辑器上传的图片名，用于记录相应的文章图片
     * @param imgSize 对应的图片大小
     * @param boTagArr 标签组
     * @param serviceId 附件临时业务id
     * @param request
     * @return
     */
    @Transactional(readOnly = false)
    public Map<String, Object> saveData(BoArticle boArticle, String imgName, String imgSize, String boTagArr, String serviceId, HttpServletRequest request){
        Map<String, Object> res = new HashMap<>();

        //添加
        if(StrUtil.isEmpty(boArticle.getId())){
            SysUser sysUser = UserUtil.getUserFromSession(request);
            boArticle.preInsert(request);
            boArticle.setUserName(sysUser.getNickName());

            //保存图片记录
            if(!StrUtil.isEmpty(imgName)){
                String[] imgNameArr = imgName.split(","); //图片名
                Integer[] imgSizeArr = Convert.toIntArray(imgSize.split(",")); //图片大小
                List<BoImgLog> boImgLogList = new ArrayList<>();
                for(int index = 0; index < imgNameArr.length; index++){
                    BoImgLog boImgLog = new BoImgLog();
                    boImgLog.preInsert();
                    boImgLog.setImgName(imgNameArr[index]);
                    boImgLog.setImgSize(imgSizeArr[index]);
                    boImgLog.setTableName("bo_article");
                    boImgLog.setTableId(boArticle.getId());
                    boImgLog.setImgPath(UploadURLUtil.ARTICLE_IMAGE_PATH);
                    boImgLogList.add(boImgLog);
                }
                if(boImgLogList.size() > 0){
                    boImgLogService.saveBatch(boImgLogList);
                }
            }

            //保存标签
            List<BoArticleTag> boArticleTagList = new ArrayList<>();
            if(!StrUtil.isEmpty(boTagArr)){
                String[] tagArr = boTagArr.split(",");
                for(String tagStr: tagArr){
                    BoArticleTag boArticleTag = new BoArticleTag();
                    boArticleTag.preInsert();
                    boArticleTag.setArticleId(boArticle.getId());
                    boArticleTag.setTagId(tagStr);
                    boArticleTagList.add(boArticleTag);
                }
                if(boArticleTagList.size() > 0){
                    boArticleTagService.saveBatch(boArticleTagList);
                }
            }

            //修改附件的业务id
            boFileService.updateServiceId(boArticle.getId(), serviceId);

            this.save(boArticle);
            res.put("state", "200");
            res.put("message", "添加成功");

            //更新
        }else{

            //保存图片记录
            if(!StrUtil.isEmpty(imgName)){
                String[] imgNameArr = imgName.split(","); //图片名
                Integer[] imgSizeArr = Convert.toIntArray(imgSize.split(",")); //图片大小
                List<BoImgLog> boImgLogList = new ArrayList<>();
                for(int index = 0; index < imgNameArr.length; index++){
                    BoImgLog boImgLog = new BoImgLog();
                    boImgLog.preInsert();
                    boImgLog.setImgName(imgNameArr[index]);
                    boImgLog.setImgSize(imgSizeArr[index]);
                    boImgLog.setTableName("bo_article");
                    boImgLog.setTableId(boArticle.getId());
                    boImgLog.setImgPath(UploadURLUtil.ARTICLE_IMAGE_PATH);
                    boImgLogList.add(boImgLog);
                }
                if(boImgLogList.size() > 0){
                    boImgLogService.saveBatch(boImgLogList);
                }
            }

            //比较封面图是否重新上传，是则删除原封面图(不是默认的封面图)
            BoArticle ba = this.getById(boArticle.getId());
            if(!boArticle.getImg().equals(ba.getImg()) && !UploadURLUtil.ARTICLE_IMAGE_NAME.equals(ba.getImg())){
                boolean flag = UploadFileUtil.deleteOneFile(UploadURLUtil.ARTICLE_IMAGE + ba.getImg());
                if(flag){
                    //删除[封面图]图片记录信息
                    boImgLogService.getBaseMapper().delete(new QueryWrapper<BoImgLog>()
                            .eq("table_name", "bo_article")
                            .eq("table_id", boArticle.getId())
                            .eq("img_name", ba.getImg()));
                    logger.info(">>>>>>>>>>>>删除封面图成功(" + ba.getImg() + ")");
                }else{
                    logger.info(">>>>>>>>>>>>删除封面图失败(" + ba.getImg() + ")");
                }
            }

            //删除文章关联的标签
            boArticleTagService.getBaseMapper().delete(new QueryWrapper<BoArticleTag>().eq("article_id", boArticle.getId()));

            //保存标签
            List<BoArticleTag> boArticleTagList = new ArrayList<>();
            if(!StrUtil.isEmpty(boTagArr)){
                String[] tagArr = boTagArr.split(",");
                for(String tagStr: tagArr){
                    BoArticleTag boArticleTag = new BoArticleTag();
                    boArticleTag.preInsert();
                    boArticleTag.setArticleId(boArticle.getId());
                    boArticleTag.setTagId(tagStr);
                    boArticleTagList.add(boArticleTag);
                }
                if(boArticleTagList.size() > 0){
                    boArticleTagService.saveBatch(boArticleTagList);
                }
            }

            //修改附件的业务id
            boFileService.updateServiceId(boArticle.getId(), serviceId);

            boArticle.preUpdate(request);
            this.updateById(boArticle);
            res.put("state", "200");
            res.put("message", "修改成功");
        }
        return res;
    }

    /**
     * 查询已删除的文章列表
     * @param params
     * @return
     */
    public List<Map<String, Object>> recycleList(Map<String, Object> params){
        return baseMapper.recycleList(params);
    }

    /**
     * 彻底删除
     * @param id
     * @return
     */
    @Transactional(readOnly = false)
    public int thoroughlyDelete(String id){
        //如果为游客文章，直接删除
        BoArticle article = this.getById(id);
        if(article.getType() == 1){
            baseMapper.thoroughlyDelete(id);
            return 1;
        }

        //查询该编辑对应的图片记录（包含封面图）
        List<BoImgLog> imgLogList = boImgLogService.getBaseMapper()
                .selectList(new QueryWrapper<BoImgLog>()
                        .eq("table_name", "bo_Article")
                        .eq("table_id", id));

        //删除图片
        boolean flag = true;
        if(imgLogList.size() > 0){
            String path = UploadURLUtil.ARTICLE_IMAGE; //路径
            String[] imgName = new String[imgLogList.size()];
            for (int i = 0; i < imgLogList.size(); i++){
                imgName[i] = path + imgLogList.get(i).getImgName();
            }
            flag = UploadFileUtil.deleteMoreFile(imgName);
            logger.info(">>>>>>>>>>>>删除图片和封面图成功<<<<<<<<<<<<<<<<");
        }

        //删除文章附件
        int fileNum = deleteFile(id);
        logger.info(">>>>>>>>>>>>删除文章附件成功：{}" + fileNum);

        //删除图片成功则删表记录
        if(flag){
            boImgLogService.getBaseMapper().delete(new QueryWrapper<BoImgLog>().eq("table_name", "bo_article")
                    .eq("table_id", id));
            logger.info(">>>>>>>>>>>>删除图片表记录成功<<<<<<<<<<<<<<<<");

            //删除标签记录
            boArticleTagService.getBaseMapper().delete(new QueryWrapper<BoArticleTag>().eq("article_id", id));

            //删除文章记录
            int i = baseMapper.thoroughlyDelete(id);
            logger.info(">>>>>>>>>>>>删除文章记录成功<<<<<<<<<<<<<<<<");
            return i;

        }else{
            return 0;
        }

    }

    /**
     * 文章附件上传
     * @param file
     * @param serviceId
     * @param request
     */
    @Transactional
    public void uploadFile(MultipartFile file, String serviceId, HttpServletRequest request){
        Map<String, Object> map = UploadFileUtil.boFileUpload(file, UploadURLUtil.FILE);
        if("200".equals(map.get("state") + "")){
            BoFile boFile = new BoFile();
            boFile.preInsert(request);
            boFile.setServiceId(serviceId);
            String name = map.get("fileName") + "";
            boFile.setFileName(name);
            boFile.setFileOrgname(map.get("fileOrgname") + "");
            boFile.setFileSize(Double.parseDouble(map.get("fileSize") + ""));
            String[] nameArr = name.split("\\.");
            boFile.setFileType(nameArr[nameArr.length - 1]);
            boFile.setCalssity(0);
            boFileService.save(boFile);
        }
    }

    /**
     * 删除文章附件
     * @param serviceId
     */
    @Transactional
    public int deleteFile(String serviceId){
        //删除记录和附件
        int num = 0;
        List<BoFile> list = boFileService.getBaseMapper().selectList(new QueryWrapper<BoFile>().eq("service_id", serviceId));
        if(ObjectUtil.isNotEmpty(list)){
            for(BoFile boFile: list){
                boolean flag = boFileService.removeById(boFile.getId());
                if(flag){
                    UploadFileUtil.deleteOneFile(UploadURLUtil.FILE + boFile.getFileName());
                    num++;
                }
            }
        }
        return num;
    }

    /**
     * 查询审核通过的文章阅读数量总数
     * @return
     */
     public int getReadNumTotal(){
        return baseMapper.getReadNumTotal();
     }

    /**
     * 查询审核通过的文章赞数量总数
     * @return
     */
    public int getPraiseNumTotal(){
        return baseMapper.getPraiseNumTotal();
    }

}